/***************************************************************************
 *   Copyright (C) 2008 by Thomas Richards   *
 *   thomi@colon   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include "plugin.h"
#include <QSettings>
#include <QByteArray>
#include <QDebug>

Plugin::Plugin(const QString &strCommandLine, QObject *parent)
 : QProcess(parent), m_strCmdLine(strCommandLine)
{
}


Plugin::~Plugin()
{
}

void Plugin::run(const QStringList &slArguments)
{
	// TODO Replace m)strCmdLine with a qstringlist, to cope with paths that have spaces in them!
	QStringList list = m_strCmdLine.split(' ', QString::SkipEmptyParts) + slArguments;
	QString strApp = list.takeFirst();
	
	start(strApp, list);
}




void Plugin::writeDefaultConfig(QSettings * pSettings)
{
	// run plugin and interrogate for default config:
	run(QStringList("--lc"));
	// shouldn't take more than 30 seconds to list default config:
	waitForFinished(30000);
	QList<QByteArray> configOptions = readAllStandardOutput().split('\n');
	
	
	foreach(QByteArray option, configOptions)
	{
		option = option.trimmed();
		if (option == "")
			break;
		
		qDebug(option);
		
		QList<QByteArray> parts = option.split(',');
		if (parts.count() < 2)
		{
			qDebug() << "Invalid config:" << parts;
			continue;
		}
			
		
		QString strName = parts.at(0);
		QString strType = parts.at(1).toLower();
		QString strDef;
		if (parts.count() == 3)
		{
			strDef = parts.at(2);
		}
		
		QVariant data;
		
		if (strType == "string")
			data = strDef;
		else if (strType == "bool")
			data = (strDef == "true");
		else if (strType == "int")
			data = strDef.toInt();
		
		pSettings->setValue(strName, data);
	}
}

